﻿using Sunny.UI;
using static WinFormsSprayProcessSCADASystem.Extension.UIDataGridViewActionCell;

namespace WinFormsSprayProcessSCADASystem.Extension
{



    /// <summary>
    /// 操作列，用于显示按钮或图标
    /// </summary>
    public class UIDataGridViewActionColumn : DataGridViewColumn
    {
        public UIDataGridViewActionColumn() : base(new UIDataGridViewActionCell())
        {
            // 设置列默认属性
            this.Width = 120;
            this.HeaderText = "操作";
            this.SortMode = DataGridViewColumnSortMode.NotSortable;
        }
        public UIDataGridViewActionColumn(ActionBtn[] btnsStr, EventHandler<ButtonClickEventArgs> buttonClick) : base(new UIDataGridViewActionCell(btnsStr, buttonClick))
        {
            // 设置列默认属性
            this.Width = 120;
            this.HeaderText = "操作";
            this.SortMode = DataGridViewColumnSortMode.NotSortable;
        }

        public override DataGridViewCell CellTemplate
        {
            get => base.CellTemplate;
            set
            {

                if (value != null)
                {
                    if (!value.GetType().IsAssignableFrom(typeof(UIDataGridViewActionCell)))
                    {
                        throw new InvalidCastException("必须是 UIDataGridViewActionCell 类型");
                    }
                }
                base.CellTemplate = value;
            }
        }

    }

    /// <summary>
    /// 操作列单元格
    /// </summary>
    public class UIDataGridViewActionCell : DataGridViewButtonCell
    {
        // 存储每行的按钮集合
        private Dictionary<int, List<UIButton>> rowButtons = new Dictionary<int, List<UIButton>>();
        //private string[] _buttonTexts;
        private ActionBtn[] _buttonInfos;
        private HashSet<int> initializedRows = new HashSet<int>(); // 记录已初始化的行
        public UIDataGridViewActionCell()
        {
            this.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        public UIDataGridViewActionCell(ActionBtn[] btnsStr, EventHandler<ButtonClickEventArgs> buttonClick)
        {
            _buttonInfos = btnsStr;
            ButtonClick += buttonClick;
            this.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

        public override object Clone()
        {
            // 调用基类的Clone方法获取克隆对象
            var clone = (UIDataGridViewActionCell)base.Clone();

            // 复制自定义属性
            clone._buttonInfos = this._buttonInfos;
            clone.ButtonClick = this.ButtonClick;

            return clone;
        }

        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
            DataGridViewElementStates elementState, object value, object formattedValue, string errorText,
            DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts)
        {
            // 绘制单元格背景
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText,
                cellStyle, advancedBorderStyle, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border);

            // 只在首次绘制或按钮未创建时初始化按钮
            if (!initializedRows.Contains(rowIndex) || !rowButtons.ContainsKey(rowIndex) || rowButtons[rowIndex] == null)
            {
                CreateButtons(rowIndex);
                initializedRows.Add(rowIndex);
            }
            else
            {
                // 如果按钮已创建，只需调整位置
                AdjustButtonPositions(rowIndex);
            }
        }

        private void CreateButtons(int rowIndex)
        {
            if (rowIndex < 0 || DataGridView == null || _buttonInfos == null || _buttonInfos.Length == 0) return;

            // 清除旧按钮
            RemoveButtons(rowIndex);

            // 创建新按钮
            List<UIButton> buttons = new List<UIButton>();
            Rectangle cellRect = DataGridView.GetCellDisplayRectangle(this.ColumnIndex, rowIndex, false);

            int buttonWidth = cellRect.Width / _buttonInfos.Length - 4;
            int x = cellRect.X + 2;

            for (int i = 0; i < _buttonInfos.Length; i++)
            {
                UIButton button = new UIButton
                {
                    Text = _buttonInfos[i].Text,
                    Size = new Size(buttonWidth, cellRect.Height - 4),
                    Location = new Point(x, cellRect.Y + 2),
                    Style = UIStyle.Custom,
                    FillColor = _buttonInfos[i].TypeColor,
                    RectColor = ControlPaint.Dark(_buttonInfos[i].TypeColor),
                    FillPressColor = ControlPaint.Dark(_buttonInfos[i].TypeColor),
                    FillHoverColor = ControlPaint.Light(_buttonInfos[i].TypeColor),
                    ForeColor = Color.White,
                    Tag = $"{rowIndex}_{i}" // 存储行号和按钮索引
                };

                button.Click += Button_Click;
                DataGridView.Controls.Add(button);
                buttons.Add(button);
                x += buttonWidth + 2;
            }

            rowButtons[rowIndex] = buttons;
        }

        private void AdjustButtonPositions(int rowIndex)
        {
            if (rowIndex < 0 || DataGridView == null || !rowButtons.ContainsKey(rowIndex)) return;

            Rectangle cellRect = DataGridView.GetCellDisplayRectangle(this.ColumnIndex, rowIndex, false);
            if (cellRect.IsEmpty) return;

            var buttons = rowButtons[rowIndex];
            int buttonWidth = cellRect.Width / buttons.Count - 4;
            int x = cellRect.X + 2;

            foreach (var button in buttons)
            {
                button.Location = new Point(x, cellRect.Y + 2);
                button.Size = new Size(buttonWidth, cellRect.Height - 4);
                x += buttonWidth + 2;
            }
        }

        private void RemoveButtons(int rowIndex)
        {
            if (rowButtons.ContainsKey(rowIndex))
            {
                foreach (var button in rowButtons[rowIndex])
                {
                    button.Click -= Button_Click;
                    if (DataGridView != null && DataGridView.Controls.Contains(button))
                    {
                        DataGridView.Controls.Remove(button);
                    }
                    button.Dispose();
                }
                rowButtons.Remove(rowIndex);
            }
        }

        // 重写方法，在单元格被回收时清理资源
        protected override void OnDataGridViewChanged()
        {
            base.OnDataGridViewChanged();

            // 清除所有按钮
            foreach (var row in rowButtons.Keys.ToList())
            {
                RemoveButtons(row);
            }
            initializedRows.Clear();
        }


        private void Button_Click(object sender, EventArgs e)
        {
            UIButton button = sender as UIButton;
            if (button == null || DataGridView == null) return;

            string[] tagParts = button.Tag.ToString().Split('_');
            if (tagParts.Length < 2) return;

            int rowIndex = int.Parse(tagParts[0]);
            int buttonIndex = int.Parse(tagParts[1]);

            //// 触发单元格点击事件
            //DataGridViewCellEventArgs args = new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex);
            //DataGridView.OnCellContentClick(args);

            // 传递按钮点击信息（通过事件或回调）
            //Console.WriteLine("传递按钮点击信息1");
            ButtonClick?.Invoke(this, new ButtonClickEventArgs(rowIndex, buttonIndex, button.Text));
        }

        // 自定义按钮点击事件
        public event EventHandler<ButtonClickEventArgs> ButtonClick;

        public class ButtonClickEventArgs : EventArgs
        {
            public int RowIndex { get; set; }
            public int ButtonIndex { get; set; }
            public string ButtonText { get; set; }

            public ButtonClickEventArgs(int rowIndex, int buttonIndex, string buttonText)
            {
                RowIndex = rowIndex;
                ButtonIndex = buttonIndex;
                ButtonText = buttonText;
            }
        }

        public class ActionBtn
        {
            public string Text { get; set; }

            // 存储按钮类型的键（如"primary", "success", "warning"）
            public ETypeKey TypeKey { get; set; }


            // 预定义的按钮类型字典
            public static readonly Dictionary<int, Color> BtnTypeEnum = new Dictionary<int, Color>
            {
                {0, Color.FromArgb(80, 160, 255)},
                {1, Color.FromArgb(240, 173, 78)},  // 修正了"success"的拼写
                {2, Color.FromArgb(217, 83, 79)}    // 修正了"warning"的拼写
            };

            // 获取按钮类型对应的颜色
            public Color TypeColor
            {
                get
                {
                    if (BtnTypeEnum.TryGetValue((int)TypeKey, out Color color))
                        return color;

                    // 默认返回黑色或其他颜色
                    return Color.Black;
                }
            }
        }
    }

    public static class UIDataGridViewExtension
    {
        /// <summary>
        /// 添加操作列
        /// </summary>
        /// <param name="gridView">DataGridView实例</param>
        /// <param name="columnName">列名称</param>
        /// <param name="width">列宽度</param>
        /// <param name="buttonTexts">按钮文本数组</param>
        /// <returns>操作列</returns>
        public static UIDataGridViewActionColumn AddActionColumn(this UIDataGridView gridView, string columnName, int width, EventHandler<ButtonClickEventArgs> buttonClick, params ActionBtn[] buttonInfos)
        {
            UIDataGridViewActionColumn column = new UIDataGridViewActionColumn(buttonInfos, buttonClick)
            {
                Name = columnName,
                HeaderText = columnName,
                Width = width,
            };

            gridView.Columns.Add(column);
            return column;
        }


    }

    public enum ETypeKey
    {
        primary,
        success,
        warning,
    }


}

